<?php

namespace App\Http\Validate\OpenShop\SiteLocation;

use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Http\Middleware\OpenShop\AppletAuth;
use App\Http\Validate\AbstractBaseValidate;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use Illuminate\Support\MessageBag;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class SiteFormValidate extends AbstractBaseValidate
{

    /**
     * 获取校验规则
     *
     * @return array
     */
    function getRules(): array
    {
        // TODO: Implement getRules() method.
        return [
            "longitude"      => "required",
            "latitude"       => "required",
            "siteAddress"    => "required",
            "cityArea"       => "required",
            "provinceCode"   => "required",
            "cityCode"       => "required",
            "areaCode"       => "required",
            "address"        => "required",
            "nearbyRange"    => "sometimes",
            "nearbyShopCode" => "sometimes",
            "messageFrom"    => "required",
            "shopModelType"  => "required",
            "cityType"       => "required",
            "leaseName"      => "sometimes|string",
            "leaseMobile"    => "required",
            "clueRent"       => "sometimes|gte:0|lte:999999999",
            "area"           => "sometimes|gte:0|lte:999",
            "clueImages"     => "sometimes|array",
            "clueVideos"     => "sometimes|array",
            "rentFreePeriod" => "sometimes",
            "deposit"        => "sometimes",
            "mallId"         => "sometimes",
            "mallName"       => "sometimes",
            "mallGrade"      => "sometimes",
            "mallStatus"     => "sometimes",
            "isWhiteList"    => "sometimes",
            "isAuditMall"    => "sometimes",
            "nearbyPlaceHolderId"    => "sometimes",
            "nearbyPlaceHolderRange" => "sometimes",
            "nearbyPlaceholderTime"  => "sometimes",
            "town"                   => "sometimes",
            "townGrade"              => "sometimes",
            "rentType"               => "sometimes",
            "rentPaymentCycle"       => "sometimes",
            "remind"                 => "sometimes",
            "wgNumber"               => "sometimes",
            "wgMatch"                => "sometimes",
            "wgGrade"                => "sometimes",
            'shopType'               => 'sometimes',
            'siteSelection'          => 'sometimes',
            'townText'               => 'sometimes',
            'recommendType'          => 'sometimes',
        ];
    }

    /**
     * 获取校验属性
     *
     * @return array
     */
    function getAttributes(): array
    {
        // TODO: Implement getAttributes() method.
        return [];
    }

    /**
     *  注册校验规则
     */
    function registerValidateRules(): void
    {
        // TODO: Implement registerValidateRules() method.
    }

    /**
     * 获取校验错误信息
     *
     * @return array
     */
    function getMessages(): array
    {
        // TODO: Implement getMessages() method.
        return [
            'longitude.required' => '经度不存在请重新选择地址',
            'latitude.required' => '纬度不存在请重新选择地址'
        ];
    }


    /**
     * @param array $requestParams
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function clueSiteLocationInsertValidate(array $requestParams)
    {
        return self::getInstance()->validate(
            [
                "longitude",
                "latitude",
                "siteAddress",
                "cityArea",
                "provinceCode",
                "cityCode",
                "areaCode",
                "address",
                "leaseName",
                "leaseMobile",
                "clueRent",
                "area",
                "rentFreePeriod",
                "deposit",
                "messageFrom",
                "shopModelType",
                "cityType",
                "nearbyShopCode",
                "nearbyRange",
                "mallId",
                "mallName",
                "mallGrade",
                "mallStatus",
                "isWhiteList",
                "isAuditMall",
                "nearbyPlaceHolderId",
                "nearbyPlaceHolderRange",
                "nearbyPlaceholderTime",
                "town",
                "townGrade",
                "rentType",
                "rentPaymentCycle",
                "remind",
                "wgNumber",
                "wgMatch",
                "wgGrade",
                'shopType',
                'siteSelection',
                'townText',
                'recommendType',
            ],
            $requestParams,
        );
    }

    /**
     * 附件校验
     *
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function attachValidate(array $requestParams)
    {
        return self::getInstance()->validate(
            ["clueImages", "clueVideos"],
            $requestParams,
            null,
            true,
            function (array $params) use ($requestParams) {
                $insertData = [];
                $uid        = AppletAuth::$userInfo ? AppletAuth::$userInfo->userId : 0;
                collect($params)->each(function ($v, $k) use (&$insertData, $requestParams, $uid) {
                    collect($v)->each(function ($img) use (&$insertData, $k, $requestParams, $uid) {
                        $position = array_keys(UploadFileResourceEnum::CLUE_SITE_LOCATION_MAP, $k)[0];
                        array_push($insertData, [
                            "position"     => $position,
                            "url"          => getPrivateFileKey($img),
                            "createdAt"    => time(),
                            "createdByUid" => $uid
                        ]);
                    });
                });
                return $insertData;
            }
        );
    }

    /**
     * 详情页校验
     *
     * @param array $requestParams
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function clueSiteLocationDetailValidate(array $requestParams)
    {
        return self::getInstance()->validate(["id"], $requestParams, [
            "id" => [
                "int",
                "required",
                Rule::exists("open_shop_site_locations", "id")
                    ->where(function ($query) {
                        $query->where("source", OpenShopSiteLocationModel::SOURCE_HOUSING)
                              ->orWhere("bindId", ">", 0)
                              ->orWhere("clueStatus", OpenShopSiteLocationModel::CLUE_STATUS_6);
                    })
            ]
        ]);
    }

    /**
     * 详情页校验
     *
     * @param array $requestParams
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function allClueDetailValidate(array $requestParams)
    {
        return self::getInstance()->validate(["id"], $requestParams, [
            "id" => [
                "int",
                "required",
                Rule::exists("open_shop_site_locations", "id")
                    ->where("source", OpenShopSiteLocationModel::SOURCE_HOUSING)
                    ->where("clueStatus", OpenShopSiteLocationModel::CLUE_STATUS_5)
            ]
        ]);
    }

    /**
     * 指派开发经理校验
     *
     * @param array $requestParams
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function assignManagerValidate(array $requestParams)
    {
        return self::getInstance()->validate(["id"], $requestParams, [
            "id"          => [
                "int",
                "required",
                Rule::exists("open_shop_site_locations", "id")
                    ->where("source", OpenShopSiteLocationModel::SOURCE_HOUSING)
                    ->where("clueStatus", OpenShopSiteLocationModel::CLUE_STATUS_1)
            ],
            "managerId"   => "required|int|gt:0",
            "managerName" => "required|string"
        ]);
    }

    /**
     * 房源线索时效校验
     *
     * @param array $requestParams
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function clueInvalidValidate(array $requestParams)
    {
        return self::getInstance()->validate(["id"], $requestParams, [
            "id" => [
                "int",
                "required",
                Rule::exists("open_shop_site_locations", "id")
                    ->where("source", OpenShopSiteLocationModel::SOURCE_HOUSING)
//                    ->where(function ($query) {
//                        $query->where("clueStatus", "<", OpenShopSiteLocationModel::CLUE_STATUS_3)
//                              ->where("clueStatus", ">", OpenShopSiteLocationModel::CLUE_STATUS_0);
//                    })
            ]
        ]);
    }

    /**
     * 房源上下架
     *
     * @param array $requestParams
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function clueUpDownValidate(array $requestParams)
    {
        return self::getInstance()->validate(["id"], $requestParams, [
            "id"   => [
                "int",
                "required",
                Rule::exists("open_shop_site_locations", "id")
                    ->whereIn("clueStatus",
                        [OpenShopSiteLocationModel::CLUE_STATUS_10, OpenShopSiteLocationModel::CLUE_STATUS_5])
                    ->where("source", OpenShopSiteLocationModel::SOURCE_HOUSING)
            ],
            "type" => "required|int|in:" . OpenShopSiteLocationModel::CLUE_STATUS_10 . "," . OpenShopSiteLocationModel::CLUE_STATUS_5
        ]);
    }
}
